//判断是否登录，未登录会直接跳到登录界面
if (sessionStorage.getItem('isLogin')==="true"&& JSON.parse(sessionStorage.getItem('userInfo') || '{}').type === 3) {
    const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
    $('.username').text(userInfo.name || '管理员');
    let infoHtml = `
                    <div class="info-item"><strong>编号：</strong>${userInfo.id || "未设置"}</div>
                    <div class="info-item"><strong>姓名：</strong>${userInfo.name || "超级管理员"}</div>
                `;
    $("#adminInfo").html(infoHtml);
}
else{
    $("#username").text("未登录");
    //页面跳转
    location.href="/LLMTchStd/manlogin"
}

// 点击用户名显示弹窗
$("#username").on("click", function() {
    $("#userModal").css("display", "flex");
    fetchAdminDetail();
});

// 关闭弹窗
$(".close-modal").on("click", function() {
    $("#userModal").hide();
});

$(window).on("click", function(e) {
    if ($(e.target).hasClass("admin-modal")) {
        $("#userModal").hide();
    }
});

// 退出登录
$("#logoutBtn").on("click", function() {
    if (confirm("确定要退出登录吗？")) {
        // 删除存储的用户信息
        sessionStorage.removeItem('userInfo');
        // 删除登录标识
        sessionStorage.removeItem('isLogin');
        // 可选：跳转到登录页或其他页面
        location.href = "/LLMTchStd/manlogin";
    }
});





//页码
var stdPage=1;
var teacherPage = 1;
var classPage = 1;

var pageSize=5;//规定好的

//是否处在搜索状态
var isSearch=0;//0为没有在搜索
var isTeacherSearch = 0;
var isClassSearch = 0;

var studData;//函数的入参,命名和函数区分
var teacherData;
var classData;

//搜索的页码
var serPage=1;
var teacherSerPage = 1;
var classSerPage = 1;

//命名要和上面页面的命名不一样
function stuPage(){
    var url;
    if(isSearch==0){
        $.ajax({
            url: '/student/count',
            type: 'GET',
            contentType: 'application/json',
            success: function(data) {
                if(data.code=="0000"){
                    //console.log(pageSize)
                    //console.log(data)
                    var value=data.data
                    $(".stuPageBox").empty()
                    $(".stuPageBox").append("<button class='btn page prevPage' title='上一页'><i class='fas fa-chevron-left'></i></button>")
                    var paggg=Math.ceil(value/pageSize)
                    //console.log(paggg)
                    for(var i=0;i<Math.ceil(value/pageSize);i++){
                        if(i==stdPage-1){
                            $(".stuPageBox").append("<button class='btn page page1 active'>"+(i+1)+"</button>")
                        }
                        else{
                            $(".stuPageBox").append("<button class='btn page page1'>"+(i+1)+"</button>")
                        }
                    }
                    $(".stuPageBox").append("<button class='btn page nextPage' title='下一页'><i class='fas fa-chevron-right'></i></button>")
                }
                else{
                    alert(data.msg)
                }
            },
            error:function(){
                alert("出错了")
            }
        })
    }
    else{
        $.ajax({
            url: '/student/serCount',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(studData),
            success: function(data) {
                if(data.code=="0000"){
                    //console.log(pageSize)
                    //console.log(data)
                    var value=data.data
                    $(".stuPageBox").empty()
                    $(".stuPageBox").append("<button class='btn page prevPage' title='上一页'><i class='fas fa-chevron-left'></i></button>")
                    var paggg=Math.ceil(value/pageSize)
                    //console.log(paggg)
                    for(var i=0;i<Math.ceil(value/pageSize);i++){
                        if(i==serPage-1){
                            $(".stuPageBox").append("<button class='btn page page1 active'>"+(i+1)+"</button>")
                        }
                        else{
                            $(".stuPageBox").append("<button class='btn page page1'>"+(i+1)+"</button>")
                        }
                    }
                    $(".stuPageBox").append("<button class='btn page nextPage' title='下一页'><i class='fas fa-chevron-right'></i></button>")
                }
                else{

                    alert(data.msg)
                }
            },
            error:function(){
                alert("出错了")
            }
        })
    }
}



function stuData(){
    if(isSearch==0){
        $.ajax({
            url:'/student/page',
            type:"post",
            contentType: 'application/json',
            data: JSON.stringify(params),
            success:function(value){
                //console.log(value)
                if(value.code=="0000"){
                    var arr = value.data
                    $(".stuContentBox tbody").empty()

                    for(var i = 0;i<arr.length;i++){

                        $(".stuContentBox tbody").append("<tr>"+
                            "<td>"+arr[i].id+"</td>"+
                            "<td>"+arr[i].name+"</td>"+
                            "<td>"+arr[i].sex+"</td>"+
                            "<td>"+arr[i].age+"</td>"+
                            "<td>"+arr[i].className+"</td>"+
                            "<td>"+arr[i].sno+"</td>"+
                            "<td>"+arr[i].phone+"</td>"+
                            "<td class='action-buttons'>" +
                            "<button class='btn icon edit editStu' title='编辑' index='"+arr[i].id+"'><i class='fas fa-edit'></i></button>"+
                            "<button class='btn icon delete deleteStu' title='删除' index='"+arr[i].id+"'><i class='fas fa-trash'></i></button>"+
                            "<button class='btn icon ai aiAnalysis' title='AI分析' index='"+arr[i].id+"'><i class='fas fa-brain'></i></button>"+
                            "</td>"+
                            "</tr>"
                        )
                    }
                }
            },
            error:function(){
                alert("出错了");
            }
        })
    }
    else{
        $.ajax({
            url:'/student/search',
            type:"post",
            contentType: 'application/json',
            data: JSON.stringify(studData),
            success:function(value) {
                console.log(value)
                if (value.code == "0000") {
                    var arr = value.data
                    console.log(arr)
                    $(".stuContentBox tbody").empty()
                    console.log("0")
                    for (var i = 0; i < arr.length; i++) {
                        console.log("1")
                        $(".stuContentBox tbody").append("<tr>" +
                            "<td>" + arr[i].id + "</td>" +
                            "<td>" + arr[i].name + "</td>" +
                            "<td>" + arr[i].sex + "</td>" +
                            "<td>" + arr[i].age + "</td>" +
                            "<td>" + arr[i].className + "</td>" +
                            "<td>" + arr[i].sno + "</td>" +
                            "<td>" + arr[i].phone + "</td>" +
                            "<td class='action-buttons'>" +
                            "<button class='btn icon edit editStu' title='编辑' index='"+arr[i].id+"'><i class='fas fa-edit'></i></button>"+
                            "<button class='btn icon delete deleteStu' title='删除' index='"+arr[i].id+"'><i class='fas fa-trash'></i></button>"+
                            "<button class='btn icon ai aiAnalysis' title='AI分析' index='"+arr[i].id+"'><i class='fas fa-brain'></i></button>"+
                            "</td>"+
                            "</tr>"
                        )
                    }
                }
                else if(value.code == "4003"){
                    $(".stuContentBox tbody").empty()
                    alert(value.msg)
                }
                else{
                    alert(value.msg)
                }
            },
            error:function(){
                alert("出错了");
            }
        })
    }
}
// Current student info storage
var currentStudentInfo = null;

// AI Analysis Modal
$(".student tbody").on("click", ".aiAnalysis", function() {
    const studentId = $(this).attr("index");

    // Show loading state
    $('#ai-analysis-modal').addClass('show');
    $('#ai-analysis-text').val('正在获取AI分析结果，请稍候...');

    // 构建请求数据，只发送学生ID
    const requestData = {
        studentId: studentId
    };

    // Make AJAX call to get analysis
    $.ajax({
        url: '/deepseek/analyze-student',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(requestData),
        success: function(response) {
            if (response.code === "0000") {
                // 存储当前学生信息用于下载
                currentStudentInfo = {
                    id: studentId,
                    analysisContent: response.data
                };

                $('#ai-analysis-text').val(response.data);
            } else {
                $('#ai-analysis-text').val('获取分析结果失败: ' + response.msg);
            }
        },
        error: function(xhr) {
            $('#ai-analysis-text').val('获取分析结果时发生错误: ' + xhr.responseJSON?.msg || '服务器错误');
        }
    });
});

// Download Word Document
$('#download-analysis-btn').click(function() {
    if (!currentStudentInfo || !currentStudentInfo.id) {
        alert('请先选择学生进行AI分析');
        return;
    }

    const analysisText = $('#ai-analysis-text').val();
    if (!analysisText || analysisText.includes('正在获取')) {
        alert('请等待分析结果加载完成');
        return;
    }

    $(this).html('<i class="fas fa-spinner fa-spin"></i> 正在生成报告...').prop('disabled', true);

    // 构建下载请求数据
    const downloadData = {
        studentInfo: {
            id: currentStudentInfo.id
        },
        analysisContent: analysisText
    };

    $.ajax({
        url: '/deepseek/download-analysis',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(downloadData),
        xhrFields: {
            responseType: 'blob'
        },
        success: function(data, status, xhr) {
            let filename = '学生AI分析报告.docx';
            const disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('filename=') !== -1) {
                filename = disposition.split('filename=')[1].replace(/"/g, '');
            }

            const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            $('#download-analysis-btn').html('<i class="fas fa-download"></i> 下载分析结果').prop('disabled', false);
        },
        error: function(xhr) {
            alert('下载失败: ' + (xhr.responseJSON?.msg || '服务器错误'));
            $('#download-analysis-btn').html('<i class="fas fa-download"></i> 下载分析结果').prop('disabled', false);
        }
    });
});


$('#download-analysis-btn').click(function() {
    if (!currentStudentInfo || !currentStudentInfo.id) {
        alert('请先选择学生进行AI分析');
        return;
    }

    const analysisText = $('#ai-analysis-text').val();
    if (!analysisText || analysisText.includes('正在获取')) {
        alert('请等待分析结果加载完成');
        return;
    }

    $(this).html('<i class="fas fa-spinner fa-spin"></i> 正在生成报告...').prop('disabled', true);

    // 构建下载请求数据
    const downloadData = {
        studentInfo: currentStudentInfo,
        analysisContent: analysisText
    };

    $.ajax({
        url: '/deepseek/download-analysis',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(downloadData),
        xhrFields: {
            responseType: 'blob'
        },
        success: function(data, status, xhr) {
            let filename = currentStudentInfo.name + '-AI分析报告.docx';
            const disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('filename=') !== -1) {
                filename = disposition.split('filename=')[1].replace(/"/g, '');
            }

            const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            $('#download-analysis-btn').html('<i class="fas fa-download"></i> 下载分析结果').prop('disabled', false);
        },
        error: function(xhr) {
            alert('下载失败: ' + (xhr.responseJSON?.msg || '服务器错误'));
            $('#download-analysis-btn').html('<i class="fas fa-download"></i> 下载分析结果').prop('disabled', false);
        }
    });
});


$('#close-ai-modal').click(function() {
    $('#ai-analysis-modal').removeClass('show');
    currentStudentInfo = null;
});

// 加载班级选项
function loadClassOptionsChoose(classSelect) {
    $.ajax({
        url: '/class/page',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify([1, 100]), // 获取前100个班级
        success: function(value) {
            if (value.code == "0000") {
                var classes = value.data;

                //var $classSelect = $('#teacher-class, #update-teacher-class, #teacher-class-filter');
                classSelect.empty();
                classSelect.append('<option value="">请选择</option>');
                classes.forEach(function(clazz) {
                    classSelect.append('<option value="' + clazz.id + '">' + clazz.name + '</option>');
                });
            }
        },
        error: function() {
            alert("加载班级选项失败");
        }
    });
}

// 加载班级选项
function loadClassOptionsAll(classSelect) {
    $.ajax({
        url: '/class/page',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify([1, 100]), // 获取前100个班级
        success: function(value) {
            if (value.code == "0000") {
                var classes = value.data;

                //var $classSelect = $('#teacher-class, #update-teacher-class, #teacher-class-filter');
                classSelect.empty();
                classSelect.append('<option value="0">全部班级</option>');
                classes.forEach(function(clazz) {
                    classSelect.append('<option value="' + clazz.id + '">' + clazz.name + '</option>');
                });
            }
        },
        error: function() {
            alert("加载班级选项失败");
        }
    });
}



//刚进入页面显示的是student,所以 要在外面查一遍
stuPage();
var params = [stdPage,pageSize]
stuData()
//加载选项
var classSelect = $('#student-box .filter-bar .filter-options #class-filter');
loadClassOptionsAll(classSelect)

$(".studentRa").click(function(){
    var index = $(this).attr("index");

    // 选中当前菜单项
    $(".sidebar-nav li").removeClass("active");
    $(this).addClass("active");

    // 隐藏所有内容盒子
    $(".content-box").hide();
    // 显示对应索引的内容盒子
    $("." + index).show();

    //清除搜索框的内容
    $('.student #search-name, #search-phone').val('');
    $('.student #class-filter').val('0');

    //搜索状态设置为0
    isSearch=0;
    serPage=1;

    //console.log("执行l")
    stuPage();
    params = [stdPage,pageSize]
    stuData()

    classSelect = $('#student-box .filter-bar .filter-options #class-filter');
    loadClassOptionsAll(classSelect)
})

//页码切换
//任意页码切换
$(".stuPageBox").on("click",".page1",function(){
    if(isSearch==0){
        if(stdPage==$(this).text()){
            alert("该页已经是第"+$(this).text()+"页")
            return
        }
        stdPage=$(this).text()
        params = [stdPage,pageSize]
    }
    else {
        if(serPage==$(this).text()){
            alert("该页已经是第"+$(this).text()+"页")
            return
        }
        serPage=$(this).text()
        var offset=(serPage-1)*pageSize
        studData.offset = offset;
    }
    stuData()
    $(this).addClass("active")
    $(this).siblings().removeClass("active")
})

//上一页切换
$(".stuPageBox").on("click",".prevPage",function(){
    if(isSearch==0){
        if(stdPage==1){
            alert("已经是第一页")
            return
        }
        stdPage--
        params = [stdPage,pageSize]
    }
    else {
        if(serPage==1){
            alert("已经是第一页")
            return
        }
        serPage--
        var offset=(serPage-1)*pageSize
        studData.offset = offset;
    }
    stuData()
    $(".stuPageBox .page1").removeClass("active")
    //索引从0开始，page从1开始
    if(isSearch==0){
        $(".stuPageBox .page1").eq(stdPage-1).addClass("active")
    }
    else{
        $(".stuPageBox .page1").eq(serPage-1).addClass("active")
    }
})

//下一页切换
$(".stuPageBox").on("click",".nextPage",function(){
    if(isSearch==0){
        if(stdPage==$(".stuPageBox .page1").length){
            alert("已经是最后一页")
            return
        }
        stdPage++
        params = [stdPage,pageSize]
    }
    else{
        if(serPage==$(".stuPageBox .page1").length){
            alert("已经是最后一页")
            return
        }
        serPage++
        var offset=(serPage-1)*pageSize
        studData.offset = offset;
    }
    stuData()
    $(".stuPageBox .page1").removeClass("active")
    if(isSearch==0){
        $(".stuPageBox .page1").eq(stdPage-1).addClass("active")
    }
    else{
        $(".stuPageBox .page1").eq(serPage-1).addClass("active")
    }
})

//添加学生弹框
$(".student .addStu").click(function(){
    //console.log("成功了")
    $('#add-student-modal #student-form').find('input, select').val(''); // 清空所有输入和选择框
    $('#add-student-modal').addClass('show');
    //加载班级选项
    classSelect = $('#add-student-modal #student-class');
    loadClassOptionsChoose(classSelect)
})

// 关闭添加弹窗（点击关闭按钮、取消按钮）
$('#add-student-modal #close-modal, #cancel-btn').click(function() {
    $('#add-student-modal').removeClass('show');
});

//学号检测
$("#add-student-modal #student-id").on("input",function(){
    if (this.value.length !== 8 && this.value.length > 0) {
        this.setCustomValidity('请输入8位学号');
    } else {
        this.setCustomValidity(''); // 清除错误提示，必须有
    }
})

//手机号检测
$("#add-student-modal #student-phone").on("input",function(){
    if (this.value.length !== 11 && this.value.length > 0) {
        this.setCustomValidity('请输入正确的手机号');
    } else {
        this.setCustomValidity(''); // 清除错误提示，必须有
    }
})

$("#student-form").on("submit", function(e){
    e.preventDefault();
//$("#add-student-modal .addStuBtn").click(function(){
    var name=$("#add-student-modal #student-name").val().trim();
    var sex=$('#add-student-modal #student-gender').val()
    var age=$("#add-student-modal #student-age").val().trim();
    var classId=$('#add-student-modal #student-class').val()
    var sno=$("#add-student-modal #student-id").val().trim();
    var phone=$("#add-student-modal #student-phone").val().trim();

    // 构建 JSON 对象
    var studentData = {
        "name": name,
        "sex": sex,
        "age": parseInt(age), // 转为整数
        "classId": classId,   // 班级 ID
        "sno": sno,
        "phone": phone,
        "password":"123456"//默认密码
    };

    $.ajax({
        url:"/student/add",
        type:"post",
        contentType: 'application/json',
        data: JSON.stringify(studentData),
        success:function(value){
            alert(value.msg)
            if(value.code=="0000"){
                //隐藏弹框
                $('#add-student-modal').removeClass('show');

                //重查一遍数据 模拟刷新
                stuPage();
                params = [stdPage,pageSize]
                stuData()
            }
            else{
                alert(value.msg)
            }



        },
        error:function(){
            alert("出错了")
        }
    })

})

var stuId
//修改学生弹框
$(".student tbody").on("click",".editStu",function(){
    //加载班级选项
    classSelect = $('#update-student-modal #stu-class');
    loadClassOptionsChoose(classSelect)

    //console.log("成功了")
    $('#update-student-modal .modal-form').find('input, select').val(''); // 清空所有输入和选择框
    //回显
    stuId=$(this).attr("index")

    $.ajax({
        url:"/student/edit",
        type:"post",
        contentType: 'application/json',
        data: JSON.stringify(stuId),
        success:function(value){
            if(value.code=="0000"){
                var student=value.data
                // 填充表单数据
                $("#stu-name").val(student.name);
                $("#stu-gender").val(student.sex);
                $("#stu-age").val(student.age);
                $("#stu-class").val(student.classId); //这里使用 classId 作为选项值
                $("#stu-id").val(student.sno); //学生表中的 sno 对应表单中的 stu-id
                $("#stu-phone").val(student.phone);
            }
            else{
                alert(value.msg)
            }

        },
        error:function(){
            alert("出错了")
        }
    })


    $('#update-student-modal').addClass('show');
})

// 关闭修改弹窗（点击关闭按钮、取消按钮）
$('#update-student-modal .close-modal, #can-btn').click(function() {
    $('#update-student-modal').removeClass('show');
});

//学号检测
$("#update-student-modal #stu-id").on("input",function(){
    if (this.value.length !== 8 && this.value.length > 0) {
        this.setCustomValidity('请输入8位学号');
    } else {
        this.setCustomValidity(''); // 清除错误提示，必须有
    }
})

//手机号检测
$("#update-student-modal #stu-phone").on("input",function(){
    if (this.value.length !== 11 && this.value.length > 0) {
        this.setCustomValidity('请输入正确的手机号');
    } else {
        this.setCustomValidity(''); // 清除错误提示，必须有
    }
})

$("#update-student-modal .modal-form").on("submit", function(e){
    e.preventDefault();

    var name=$("#update-student-modal #stu-name").val().trim();
    var sex=$('#update-student-modal #stu-gender').val()
    var age=$("#update-student-modal #stu-age").val().trim();
    var classId=$('#update-student-modal #stu-class').val()
    var sno=$("#update-student-modal #stu-id").val().trim();
    var phone=$("#update-student-modal #stu-phone").val().trim();

    // 构建 JSON 对象
    var studentData = {
        "id":stuId,//全局变量
        "name": name,
        "sex": sex,
        "age": parseInt(age), // 转为整数
        "classId": classId,   // 班级 ID
        "sno": sno,
        "phone": phone
    };

    $.ajax({
        url:"/student/update",
        type:"post",
        contentType: 'application/json',
        data: JSON.stringify(studentData),
        success:function(value){
            alert(value.msg)
            if(value.code=="0000"){
                //隐藏弹框
                $('#update-student-modal').removeClass('show');

                //重查一遍数据 模拟刷新
                stuPage();
                params = [stdPage,pageSize]
                stuData()
            }



        },
        error:function(){
            alert("出错了")
        }
    })

})

//学生删除
$(".student tbody").on("click",".deleteStu",function(){
    if(confirm("确定要删除吗？")){
        var id = $(this).attr("index");
        $.ajax({
            url:"/student/delete",
            type:"post",
            contentType: 'application/json',
            data: JSON.stringify(id),
            success:function(value){
                alert(value.msg)
                if(value.code=="0000"){
                    //重查一遍数据 模拟刷新
                    stuPage();
                    params = [stdPage,pageSize]
                    stuData()
                }

            },
            error:function(){
                alert("出错了")
            }
        })
    }
    else{
        alert("已取消删除")
    }
})




//学生搜索
$("#student-box  .search-boxes #search-btn").click(function(){
    //搜索状态设置为1
    isSearch=1;
    console.log("6")
    //读取 搜索框的输入
    // 获取输入框的值
    var name = $('#student-box #search-name').val().trim();
    var phone = $('#student-box #search-phone').val().trim();


    // 获取下拉框的值
    var classId = $('#student-box #class-filter').val();
    var offset=(serPage-1)*pageSize
    console.log("66")
    studData = {
        "name": name,
        "phone": phone,
        "classId":classId,
        "offset":offset,
        "pageSize":pageSize
    };
    stuPage()
    stuData()
})

// 班级分页函数
function classPageFunc() {
    if (isClassSearch == 0) {
        $.ajax({
            url: '/class/count',
            type: 'GET',
            contentType: 'application/json',
            success: function(data) {
                if (data.code == "0000") {
                    var value = data.data;
                    $(".classPageBox").empty();
                    $(".classPageBox").append("<button class='btn page classPrevPage' title='上一页'><i class='fas fa-chevron-left'></i></button>");

                    for (var i = 0; i < Math.ceil(value / pageSize); i++) {
                        if (i == classPage - 1) {
                            $(".classPageBox").append("<button class='btn page classPage1 active'>" + (i + 1) + "</button>");
                        } else {
                            $(".classPageBox").append("<button class='btn page classPage1'>" + (i + 1) + "</button>");
                        }
                    }

                    $(".classPageBox").append("<button class='btn page classNextPage' title='下一页'><i class='fas fa-chevron-right'></i></button>");
                } else {
                    alert(data.msg);
                }
            },
            error: function() {
                alert("出错了");
            }
        });
    } else {
        $.ajax({
            url: '/class/serCount',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(classData),
            success: function(data) {
                if (data.code == "0000") {
                    var value = data.data;
                    $(".classPageBox").empty();
                    $(".classPageBox").append("<button class='btn page classPrevPage' title='上一页'><i class='fas fa-chevron-left'></i></button>");

                    for (var i = 0; i < Math.ceil(value / pageSize); i++) {
                        if (i == serPage - 1) {
                            $(".classPageBox").append("<button class='btn page classPage1 active'>" + (i + 1) + "</button>");
                        } else {
                            $(".classPageBox").append("<button class='btn page classPage1'>" + (i + 1) + "</button>");
                        }
                    }

                    $(".classPageBox").append("<button class='btn page classNextPage' title='下一页'><i class='fas fa-chevron-right'></i></button>");
                } else {
                    alert(data.msg);
                }
            },
            error: function() {
                alert("出错了");
            }
        });
    }
}

// 班级数据加载函数
function classDataFunc() {
    var params = [classPage, pageSize];

    if (isClassSearch == 0) {
        $.ajax({
            url: '/class/page',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(params),
            success: function(value) {
                if (value.code == "0000") {
                    var arr = value.data;
                    $(".classContentBox tbody").empty();

                    for (var i = 0; i < arr.length; i++) {
                        $(".classContentBox tbody").append("<tr>" +
                            "<td>" + arr[i].id + "</td>" +
                            "<td>" + arr[i].name + "</td>" +
                            "<td>" + (arr[i].studentCount || 0) + "</td>" +
                            "<td>" + (arr[i].teacherName || '未分配') + "</td>" +
                            "<td class='action-buttons'>" +
                            "<button class='btn icon edit editClass' title='编辑' index='" + arr[i].id + "'><i class='fas fa-edit'></i></button>" +
                            "<button class='btn icon delete deleteClass' title='删除' index='" + arr[i].id + "'><i class='fas fa-trash'></i></button>" +
                            "</td>" +
                            "</tr>");
                    }
                }
            },
            error: function() {
                alert("出错了");
            }
        });
    } else {
        $.ajax({
            url: '/class/search',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(classData),
            success: function(value) {
                if (value.code == "0000") {
                    var arr = value.data;
                    $(".classContentBox tbody").empty();

                    for (var i = 0; i < arr.length; i++) {
                        $(".classContentBox tbody").append("<tr>" +
                            "<td>" + arr[i].id + "</td>" +
                            "<td>" + arr[i].name + "</td>" +
                            "<td>" + (arr[i].studentCount || 0) + "</td>" +
                            "<td>" + (arr[i].teacherName || '未分配') + "</td>" +
                            "<td class='action-buttons'>" +
                            "<button class='btn icon edit editClass' title='编辑' index='" + arr[i].id + "'><i class='fas fa-edit'></i></button>" +
                            "<button class='btn icon delete deleteClass' title='删除' index='" + arr[i].id + "'><i class='fas fa-trash'></i></button>" +
                            "</td>" +
                            "</tr>");
                    }
                }
                else if(value.code == "4003"){
                    $(".classContentBox tbody").empty();
                    alert(value.msg)
                }
                else{
                    alert(value.msg)
                }

            },
            error: function() {
                alert("出错了");
            }
        });
    }
}


// 班级分页切换
$(".classPageBox").on("click", ".classPage1", function() {
    if(isClassSearch==0){
        if(classPage==$(this).text()){
            alert("该页已经是第"+$(this).text()+"页")
            return
        }
        classPage=$(this).text()
        params = [classPage,pageSize]
    }
    else {
        if(serPage==$(this).text()){
            alert("该页已经是第"+$(this).text()+"页")
            return
        }
        serPage=$(this).text()
        var offset=(serPage-1)*pageSize
        classData.offset = offset;
    }
    classDataFunc()
    $(this).addClass("active")
    $(this).siblings().removeClass("active")
})

// 班级上一页
$(".classPageBox").on("click", ".classPrevPage", function() {
    if(isClassSearch==0){
        if(classPage==1){
            alert("已经是第一页")
            return
        }
        classPage--
        params = [classPage,pageSize]
    }
    else {
        if(serPage==1){
            alert("已经是第一页")
            return
        }
        serPage--
        var offset=(serPage-1)*pageSize
        classData.offset = offset;
    }
    classDataFunc()
    $(".classPageBox .classPage1").removeClass("active")
    if(isClassSearch==0){
        $(".classPageBox .classPage1").eq(classPage-1).addClass("active")
    }
    else{
        $(".classPageBox .classPage1").eq(serPage-1).addClass("active")
    }
})

// 班级下一页
$(".classPageBox").on("click", ".classNextPage", function() {
    if(isClassSearch==0){
        if(classPage==$(".classPageBox .classPage1").length){
            alert("已经是最后一页")
            return
        }
        classPage++
        params = [classPage,pageSize]
    }
    else{
        if(serPage==$(".classPageBox .classPage1").length){
            alert("已经是最后一页")
            return
        }
        serPage++
        var offset=(serPage-1)*pageSize
        classData.offset = offset;
    }
    classDataFunc()
    $(".classPageBox .classPage1").removeClass("active")
    if(isClassSearch==0){
        $(".classPageBox .classPage1").eq(classPage-1).addClass("active")
    }
    else{
        $(".classPageBox .classPage1").eq(serPage-1).addClass("active")
    }
})


// 添加班级弹窗
$(".addClass").click(function() {
    $('#add-class-modal #class-form').find('input').val('');
    $('#add-class-modal').addClass('show');
});

// 关闭添加班级弹窗
$('#close-class-modal, #cancel-class-btn').click(function() {
    $('#add-class-modal').removeClass('show');
});

// 提交添加班级表单
$("#class-form").on("submit", function(e) {
    e.preventDefault();

    var className = $("#class-name").val().trim();
    var teacherId = $("#class-teacher").val();

    if (!className) {
        alert("请输入班级名称");
        return;
    }

    var classData = {
        "name": className,
        "teacherId": teacherId
    };

    $.ajax({
        url: "/class/add",
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify(classData),
        success: function(value) {
            if (value.code == "4004") {
                alert(value.msg); // 显示班级名称已存在的错误
                return;
            }
            alert(value.msg);
            if (value.code == "0000") {
                $('#add-class-modal').removeClass('show');
                classPageFunc();
                classDataFunc();
            }
        },
        error: function() {
            alert("出错了");
        }
    });
});

// 编辑班级弹窗
var editClassId;
$(".classContentBox").on("click", ".editClass", function() {
    editClassId = $(this).attr("index");
    $('#update-class-modal #update-class-form').find('input, select').val('');

    $.ajax({
        url: "/class/edit",
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify(editClassId),
        success: function(value) {
            if (value.code == "0000") {
                $("#update-class-name").val(value.data.name);
                $("#update-class-teacher").val(value.data.teacherId || '');
                $('#update-class-modal').addClass('show');
            } else {
                alert(value.msg);
            }
        },
        error: function() {
            alert("出错了");
        }
    });
});

// 关闭编辑班级弹窗
$('#close-update-class-modal, #cancel-update-class-btn').click(function() {
    $('#update-class-modal').removeClass('show');
});

// 提交编辑班级表单
$("#update-class-form").on("submit", function(e) {
    e.preventDefault();

    var className = $("#update-class-name").val().trim();
    var teacherId = $("#update-class-teacher").val();

    if (!className) {
        alert("请输入班级名称");
        return;
    }

    var classData = {
        "id": editClassId,
        "name": className,
        "teacherId": teacherId
    };

    $.ajax({
        url: "/class/update",
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify(classData),
        success: function(value) {
            if (value.code == "4004") {
                alert(value.msg); // 显示班级名称已被使用的错误
                return;
            }
            alert(value.msg);
            if (value.code == "0000") {
                $('#update-class-modal').removeClass('show');
                classPageFunc();
                classDataFunc();
            }
        },
        error: function() {
            alert("出错了");
        }
    });
});

// 删除班级
$(".classContentBox").on("click", ".deleteClass", function() {
    if (confirm("确定要删除这个班级吗？")) {
        var id = $(this).attr("index");

        $.ajax({
            url: "/class/delete",
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify(id),
            success: function(value) {
                alert(value.msg);
                if (value.code == "0000") {
                    classPageFunc();
                    classDataFunc();
                }
            },
            error: function() {
                alert("出错了");
            }
        });

    } else {
        alert("已取消删除");
    }
});

// 页面加载时初始化班级选项
$(document).ready(function() {
    loadClassOptions();
    loadTeacherOptions(); // 添加这行
});


// 班级搜索
$("#search-class-btn").click(function() {
    // 读取搜索框的输入
    var name = $("#search-class-name").val().trim();
    if(name===""){
        alert("请输入数据")
        return
    }

    // 搜索状态设置为1
    isClassSearch = 1;

    // 重置页码
    serPage = 1;
    classPage = 1;


    var offset = (serPage-1)*pageSize;

    classData = {
        "name": name,
        "offset": offset,
        "pageSize": pageSize
    };



    // 调用分页和数据加载函数
    classPageFunc();
    params = [classPage,pageSize]
    classDataFunc();
});

$(".classRa").click(function() {
    var index = $(this).attr("index");

    $(".sidebar-nav li").removeClass("active");
    $(this).addClass("active");

    $(".content-box").hide();
    $("." + index).show();

    // 清除搜索框内容
    $('#search-class-name').val('');

    // 重置搜索状态
    isClassSearch = 0;
    serPage = 1;

    // 加载班级数据
    classPageFunc();
    classDataFunc();
});

// 加载班级选项
function loadClassOptions() {
    $.ajax({
        url: '/class/page',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify([1, 100]), // 获取前100个班级
        success: function(value) {
            if (value.code == "0000") {
                var classes = value.data;
                // 更新添加教师弹窗的班级选项
                var $classSelect = $('#teacher-class, #update-teacher-class, #teacher-class-filter');
                $classSelect.empty();
                $classSelect.append('<option value="">请选择</option>');

                classes.forEach(function(clazz) {
                    $classSelect.append('<option value="' + clazz.id + '">' + clazz.name + '</option>');
                });
            }
        },
        error: function() {
            alert("加载班级选项失败");
        }
    });
}

// 教师分页函数
function teacherPageFunc() {
    var url;
    if (isTeacherSearch == 0) {
        $.ajax({
            url: '/teacher/count',
            type: 'GET',
            contentType: 'application/json',
            success: function(data) {
                if (data.code == "0000") {
                    var value = data.data;
                    $(".teacherPageBox").empty();
                    $(".teacherPageBox").append("<button class='btn page teacherPrevPage' title='上一页'><i class='fas fa-chevron-left'></i></button>");

                    for (var i = 0; i < Math.ceil(value / pageSize); i++) {
                        if (i == teacherPage - 1) {
                            $(".teacherPageBox").append("<button class='btn page teacherPage1 active'>" + (i + 1) + "</button>");
                        } else {
                            $(".teacherPageBox").append("<button class='btn page teacherPage1'>" + (i + 1) + "</button>");
                        }
                    }

                    $(".teacherPageBox").append("<button class='btn page teacherNextPage' title='下一页'><i class='fas fa-chevron-right'></i></button>");
                } else {
                    alert(data.msg);
                }
            },
            error: function() {
                alert("获取教师数量失败");
            }
        });
    } else {
        $.ajax({
            url: '/teacher/serCount',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(teacherData),
            success: function(data) {
                if (data.code == "0000") {
                    var value = data.data;
                    $(".teacherPageBox").empty();
                    $(".teacherPageBox").append("<button class='btn page teacherPrevPage' title='上一页'><i class='fas fa-chevron-left'></i></button>");

                    for (var i = 0; i < Math.ceil(value / pageSize); i++) {
                        if (i == serPage - 1) {
                            $(".teacherPageBox").append("<button class='btn page teacherPage1 active'>" + (i + 1) + "</button>");
                        } else {
                            $(".teacherPageBox").append("<button class='btn page teacherPage1'>" + (i + 1) + "</button>");
                        }
                    }

                    $(".teacherPageBox").append("<button class='btn page teacherNextPage' title='下一页'><i class='fas fa-chevron-right'></i></button>");
                } else {
                    alert(data.msg);
                }
            },
            error: function() {
                alert("获取搜索教师数量失败");
            }
        });
    }
}

// 教师数据加载函数
function teacherDataFunc() {
    var params = [teacherPage, pageSize];

    if (isTeacherSearch == 0) {
        $.ajax({
            url: '/teacher/page',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(params),
            success: function(value) {
                if (value.code == "0000") {
                    var arr = value.data;
                    $(".teacherContentBox tbody").empty();

                    for (var i = 0; i < arr.length; i++) {
                        $(".teacherContentBox tbody").append("<tr>" +
                            "<td>" + arr[i].id + "</td>" +
                            "<td>" + arr[i].name + "</td>" +
                            "<td>" + arr[i].sex + "</td>" +
                            "<td>" + arr[i].age + "</td>" +
                            "<td>" + (arr[i].className || '未分配') + "</td>" +
                            "<td>" + arr[i].workNo + "</td>" +
                            "<td>" + arr[i].phone + "</td>" +
                            "<td class='action-buttons'>" +
                            "<button class='btn icon edit editTeacher' title='编辑' index='" + arr[i].id + "'><i class='fas fa-edit'></i></button>" +
                            "<button class='btn icon delete deleteTeacher' title='删除' index='" + arr[i].id + "'><i class='fas fa-trash'></i></button>" +
                            "</td>" +
                            "</tr>");
                    }
                }
            },
            error: function() {
                alert("获取教师列表失败");
            }
        });
    }
    else {
        //teacherData.page = teacherPage;
        //teacherData.pageSize = pageSize;

        $.ajax({
            url: '/teacher/search',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(teacherData),
            success: function(value) {
                if (value.code == "0000") {
                    var arr = value.data;
                    $(".teacherContentBox tbody").empty();

                    for (var i = 0; i < arr.length; i++) {
                        $(".teacherContentBox tbody").append("<tr>" +
                            "<td>" + arr[i].id + "</td>" +
                            "<td>" + arr[i].name + "</td>" +
                            "<td>" + arr[i].sex + "</td>" +
                            "<td>" + arr[i].age + "</td>" +
                            "<td>" + (arr[i].className || '未分配') + "</td>" +
                            "<td>" + arr[i].workNo + "</td>" +
                            "<td>" + arr[i].phone + "</td>" +
                            "<td class='action-buttons'>" +
                            "<button class='btn icon edit editTeacher' title='编辑' index='" + arr[i].id + "'><i class='fas fa-edit'></i></button>" +
                            "<button class='btn icon delete deleteTeacher' title='删除' index='" + arr[i].id + "'><i class='fas fa-trash'></i></button>" +
                            "</td>" +
                            "</tr>");
                    }
                }
                else if(value.code === "4003"){
                    $(".teacherContentBox tbody").empty();
                    alert(value.msg)
                }
                else{
                    alert(value.msg)
                }
            },
            error: function() {
                alert("搜索教师失败");
            }
        });
    }
}

// 教师分页切换
$(".teacherPageBox").on("click", ".teacherPage1", function() {
    if(isTeacherSearch==0){
        if(teacherPage==$(this).text()){
            alert("该页已经是第"+$(this).text()+"页")
            return
        }
        teacherPage=$(this).text()
        params = [teacherPage,pageSize]
    }
    else {
        if(serPage==$(this).text()){
            alert("该页已经是第"+$(this).text()+"页")
            return
        }
        serPage=$(this).text()
        var offset=(serPage-1)*pageSize
        teacherData.offset = offset;
    }
    teacherDataFunc()
    $(this).addClass("active")
    $(this).siblings().removeClass("active")
})

// 教师上一页
$(".teacherPageBox").on("click", ".teacherPrevPage", function() {
    if(isTeacherSearch==0){
        if(teacherPage==1){
            alert("已经是第一页")
            return
        }
        teacherPage--
        params = [teacherPage,pageSize]
    }
    else {
        if(serPage==1){
            alert("已经是第一页")
            return
        }
        serPage--
        var offset=(serPage-1)*pageSize
        teacherData.offset = offset;
    }
    teacherDataFunc()
    $(".teacherPageBox .teacherPage1").removeClass("active")
    if(isTeacherSearch==0){
        $(".teacherPageBox .teacherPage1").eq(teacherPage-1).addClass("active")
    }
    else{
        $(".teacherPageBox .teacherPage1").eq(serPage-1).addClass("active")
    }
})

// 教师下一页
$(".teacherPageBox").on("click", ".teacherNextPage", function() {
    if(isTeacherSearch==0){
        if(teacherPage==$(".teacherPageBox .teacherPage1").length){
            alert("已经是最后一页")
            return
        }
        teacherPage++
        params = [teacherPage,pageSize]
    }
    else{
        if(serPage==$(".teacherPageBox .teacherPage1").length){
            alert("已经是最后一页")
            return
        }
        serPage++
        var offset=(serPage-1)*pageSize
        teacherData.offset = offset;
    }
    teacherDataFunc()
    $(".teacherPageBox .teacherPage1").removeClass("active")
    if(isTeacherSearch==0){
        $(".teacherPageBox .teacherPage1").eq(teacherPage-1).addClass("active")
    }
    else{
        $(".teacherPageBox .teacherPage1").eq(serPage-1).addClass("active")
    }
})

// 教师搜索
$("#search-teacher-btn").click(function() {
    // 搜索状态设置为1
    isTeacherSearch = 1;

    // 重置页码
    serPage = 1;
    teacherPage = 1;

    // 读取搜索框的输入
    var name = $('#search-teacher-name').val().trim();
    var phone = $('#search-teacher-phone').val().trim();
    var classId = $('#teacher-class-filter').val();
    var offset = (serPage-1)*pageSize;

    teacherData = {
        "name": name,
        "phone": phone,
        "classId": classId,
        "offset": offset,
        "pageSize": pageSize
    };



    // 调用分页和数据加载函数
    teacherPageFunc();
    teacherDataFunc();
});

$(".teacherRa").click(function() {
    var index = $(this).attr("index");

    $(".sidebar-nav li").removeClass("active");
    $(this).addClass("active");

    $(".content-box").hide();
    $("." + index).show();

    // 清除搜索框内容
    $('#search-teacher-name, #search-teacher-phone').val('');
    $('#teacher-class-filter').val('');

    // 重置搜索状态
    isTeacherSearch = 0;
    serPage = 1;

    // 加载教师数据
    teacherPageFunc();
    teacherDataFunc();
});

// 添加教师弹窗
$(".addTeacher").click(function() {
    $('#add-teacher-modal #teacher-form').find('input, select').val('');
    $('#add-teacher-modal').addClass('show');
});

// 关闭添加教师弹窗
$('#close-teacher-modal, #cancel-teacher-btn').click(function() {
    $('#add-teacher-modal').removeClass('show');
});

// 工号检测
$("#add-teacher-modal #teacher-work-no").on("input", function() {
    if (this.value.length !== 8 && this.value.length > 0) {
        this.setCustomValidity('请输入8位工号');
    } else {
        this.setCustomValidity('');
    }
});

// 手机号检测
$("#add-teacher-modal #teacher-phone").on("input", function() {
    if (this.value.length !== 11 && this.value.length > 0) {
        this.setCustomValidity('请输入正确的手机号');
    } else {
        this.setCustomValidity('');
    }
});

// 提交添加教师表单
$("#teacher-form").on("submit", function(e) {
    e.preventDefault();

    var name = $("#teacher-name").val().trim();
    var sex = $('#teacher-gender').val();
    var age = $("#teacher-age").val().trim();
    var classId = $('#teacher-class').val();
    var workNo = $("#teacher-work-no").val().trim();
    var phone = $("#teacher-phone").val().trim();

    var teacherData = {
        "name": name,
        "sex": sex,
        "age": parseInt(age),
        "classId": classId,
        "workNo": workNo,
        "phone": phone,
        "password": "123456" // 默认密码
    };

    $.ajax({
        url: "/teacher/add",
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify(teacherData),
        success: function(value) {
            alert(value.msg);
            if (value.code == "0000") {
                $('#add-teacher-modal').removeClass('show');
                teacherPageFunc();
                teacherDataFunc();
            }
        },
        error: function() {
            alert("添加教师失败");
        }
    });
});

// 编辑教师弹窗
var editTeacherId;
$(".teacherContentBox").on("click", ".editTeacher", function() {
    editTeacherId = $(this).attr("index");
    $('#update-teacher-modal #update-teacher-form').find('input, select').val('');

    $.ajax({
        url: "/teacher/edit",
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify(editTeacherId),
        success: function(value) {
            if (value.code == "0000") {
                var teacher = value.data;
                $("#update-teacher-name").val(teacher.name);
                $("#update-teacher-gender").val(teacher.sex);
                $("#update-teacher-age").val(teacher.age);
                $("#update-teacher-class").val(teacher.classId);
                $("#update-teacher-work-no").val(teacher.workNo);
                $("#update-teacher-phone").val(teacher.phone);
                $('#update-teacher-modal').addClass('show');
            } else {
                alert(value.msg);
            }
        },
        error: function() {
            alert("获取教师信息失败");
        }
    });
});

// 关闭编辑教师弹窗
$('#close-update-teacher-modal, #cancel-update-teacher-btn').click(function() {
    $('#update-teacher-modal').removeClass('show');
});

// 工号检测（修改）
$("#update-teacher-modal #update-teacher-work-no").on("input", function() {
    if (this.value.length !== 6 && this.value.length > 0) {
        this.setCustomValidity('请输入6位工号');
    } else {
        this.setCustomValidity('');
    }
});

// 手机号检测（修改）
$("#update-teacher-modal #update-teacher-phone").on("input", function() {
    if (this.value.length !== 11 && this.value.length > 0) {
        this.setCustomValidity('请输入正确的手机号');
    } else {
        this.setCustomValidity('');
    }
});

// 提交编辑教师表单
$("#update-teacher-form").on("submit", function(e) {
    e.preventDefault();

    var name = $("#update-teacher-name").val().trim();
    var sex = $('#update-teacher-gender').val();
    var age = $("#update-teacher-age").val().trim();
    var classId = $('#update-teacher-class').val();
    var workNo = $("#update-teacher-work-no").val().trim();
    var phone = $("#update-teacher-phone").val().trim();

    var teacherData = {
        "id": editTeacherId,
        "name": name,
        "sex": sex,
        "age": parseInt(age),
        "classId": classId,
        "workNo": workNo,
        "phone": phone
    };

    $.ajax({
        url: "/teacher/update",
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify(teacherData),
        success: function(value) {
            alert(value.msg);
            if (value.code == "0000") {
                $('#update-teacher-modal').removeClass('show');
                teacherPageFunc();
                teacherDataFunc();
            }
        },
        error: function() {
            alert("更新教师信息失败");
        }
    });
});

// 删除教师
$(".teacherContentBox").on("click", ".deleteTeacher", function() {
    if (confirm("确定要删除这位教师吗？")) {
        var id = $(this).attr("index");

        $.ajax({
            url: "/teacher/delete",
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify(id),
            success: function(value) {
                alert(value.msg);
                if (value.code == "0000") {
                    teacherPageFunc();
                    teacherDataFunc();
                }
            },
            error: function() {
                alert("删除教师失败");
            }
        });
    } else {
        alert("已取消删除");
    }
});

// 加载教师选项
function loadTeacherOptions() {
    $.ajax({
        url: '/teacher/page',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify([1, 100]), // 获取前100个教师
        success: function(value) {
            if (value.code == "0000") {
                var teachers = value.data;
                // 更新添加班级弹窗的教师选项
                var $teacherSelect = $('#class-teacher, #update-class-teacher');
                $teacherSelect.empty();
                $teacherSelect.append('<option value="">请选择</option>');

                teachers.forEach(function(teacher) {
                    $teacherSelect.append('<option value="' + teacher.id + '">' + teacher.name + '</option>');
                });
            }
        },
        error: function() {
            alert("加载教师选项失败");
        }
    });
}
